﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ChungNhanSinhVien.Entities;
using ChungNhanSinhVien.Models;
using ChungNhanSinhVien.Infrastructures;
using ChungNhanSinhVien.Entities.SinhVien;

namespace ChungNhanSinhVien.Controllers
{
    public class DangNhapController : Controller
    {
        //
        // GET: /DangNhap/

        public ActionResult Index()
        {
            if (SessionManager.nsr != null)
            {
                return RedirectToAction("LayYeuCau","Ad_YeuCau");
            }
            ViewData["err"] = "";
            return View();
        }

        [HttpPost]
        public ActionResult Index(AdminAccount model, FormCollection form)
        {
            var btn = Request.Params.AllKeys.FirstOrDefault(key => key.Equals("DangNhap"));
            if (btn != null)
            {
                AdminAccountRepository aaRepo = new AdminAccountRepository();
                AdminAccount acc = new AdminAccount();
                if (model != null && aaRepo.KiemTraTaiKhoan(model.TenDangNhap, model.MatKhau, out acc))
                {
                    SessionManager.nsr = acc;
                    SessionManager.user = null;
                    return RedirectToAction("LayYeuCau", "Ad_YeuCau");
                }
                else
                {
                    ViewData["err"] = "dangnhapthatbai";
                    return View();
                }
            }
            return View();
        }

        public ActionResult ThoatAdmin()
        {
            SessionManager.Logout();
            return RedirectToAction("Index", "DangNhap");
        }

        public ActionResult Thoat()
        {
            SessionManager.Logout();
            return RedirectToAction("UserDangNhap", "DangNhap");
        }

        public ActionResult UserDangNhap()
        {
            ViewData["err"] = "";
            return View();
        }

        [HttpPost]
        public ActionResult UserDangNhap(Student model)
        {
            var btn = Request.Params.AllKeys.FirstOrDefault(key => key.Equals("DangNhap"));
            if (btn != null)
            {
                StudentRepository stdRepo = new StudentRepository();
                SinhVien acc = new SinhVien();
                if (model != null && stdRepo.KiemTraTaiKhoan(model.StudentID, model.MatKhau, out acc))
                {
                    SessionManager.nsr = null;
                    SessionManager.user = acc;
                    return RedirectToAction("GhiNhanYeuCau", "YeuCau");
                }
                else
                {
                    ViewData["err"] = "dangnhapthatbai";
                    return View();
                }
            }
            return View();
        }
    }
}
